package com.uzai.console.service.sop.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.sop.soptask.SopTaskDto;
import com.uzai.console.dto.sop.soptask.SopTaskIdDto;
import com.uzai.console.dto.sop.soptask.SopTaskQuery;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.Merchant;
import com.uzai.console.entity.SopTask;
import com.uzai.console.enums.SopTaskStatusEnum;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.mapper.SopTaskAddInfoMapper;
import com.uzai.console.mapper.SopTaskMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.sop.SopTaskService;
import com.uzai.console.service.sop.SopTaskSyncService;
import com.uzai.console.vo.sop.soptask.SopTaskQueryParaVo;
import com.uzai.console.vo.sop.soptask.SopTaskVo;
import com.uzai.console.vo.user.SysTagVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * SOP任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class SopTaskServiceImpl implements SopTaskService {

    Logger logger = LoggerFactory.getLogger(SopTaskServiceImpl.class);

    @Autowired
    private SopTaskMapper sopTaskMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SopTaskSyncService sopTaskSyncService;
    @Autowired
    private SopTaskAddInfoMapper sopTaskAddInfoMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 查询SOP任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskQuery
     * @return null
     */
    public Page<SopTaskVo> findSopTaskList(SopTaskQuery sopTaskQuery){

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<SopTaskVo> sopTaskVoList = new ArrayList<>();

        //执行分页查询对象
        Page<SopTask> page = new Page<>();
        sopTaskQuery.convert(page);
        List<SopTask> sopTaskList = sopTaskMapper.findByList(page, sopTaskQuery);
        if(sopTaskList != null){
            for (SopTask sopTask : sopTaskList){
                SopTaskVo sopTaskVo = new SopTaskVo();
                BeanUtils.copyProperties(sopTask, sopTaskVo);

                //状态名称
                if(sopTask.getStatus() != null){
                    SopTaskStatusEnum sopTaskStatusEnum = SopTaskStatusEnum.getById(sopTask.getStatus());
                    if(sopTaskStatusEnum != null){
                        sopTaskVo.setStatusName(sopTaskStatusEnum.getDesc());
                    }
                }

                //查询条件
                if(StringUtils.isNotBlank(sopTask.getQueryPara())){
                    SopTaskQueryParaVo sopTaskQueryParaVo = JSONObject.parseObject(sopTask.getQueryPara(), SopTaskQueryParaVo.class);
                    sopTaskVo.setRedPacketTypeList(sopTaskQueryParaVo.getRedPacketTypeList());
                    sopTaskVo.setQueryTime(sopTaskQueryParaVo.getQueryTime());
                    sopTaskVo.setDeviceType(sopTaskQueryParaVo.getDeviceType());
                    sopTaskVo.setDeviceUniqueIdList(sopTaskQueryParaVo.getDeviceUniqueIdList());
                }

                //发送频率
                sopTaskVo.setRate(sopTask.getRateMax());

                sopTaskVoList.add(sopTaskVo);
            }
        }
        //返回到页面分页对象
        Page<SopTaskVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(sopTaskVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询SOP任务详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskIdDto
     * @return null
     */
    public SopTaskVo findSopTask(SopTaskIdDto sopTaskIdDto){
        //返回到页面的VO对象
        SopTaskVo sopTaskVo = new SopTaskVo();

        if(sopTaskIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SopTask sopTask = sopTaskMapper.selectById(sopTaskIdDto.getId(), sopTaskIdDto.getMerId());

        if(sopTask == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(sopTask, sopTaskVo);


        //状态名称
        if(sopTask.getStatus() != null){
            SopTaskStatusEnum sopTaskStatusEnum = SopTaskStatusEnum.getById(sopTask.getStatus());
            if(sopTaskStatusEnum != null){
                sopTaskVo.setStatusName(sopTaskStatusEnum.getDesc());
            }
        }

        //会员标签
        if(StringUtils.isNotBlank(sopTask.getUserTags())){
            sopTaskVo.setUserTagsList(JSONObject.parseArray(sopTask.getUserTags(), SysTagVo.class));
        }

        //自定义标签
        if(StringUtils.isNotBlank(sopTask.getTags())){
            sopTaskVo.setTagsList(JSONObject.parseArray(sopTask.getTags(), String.class));
        }

        //查询条件
        if(StringUtils.isNotBlank(sopTask.getQueryPara())){
            SopTaskQueryParaVo sopTaskQueryParaVo = JSONObject.parseObject(sopTask.getQueryPara(), SopTaskQueryParaVo.class);
            sopTaskVo.setRedPacketTypeList(sopTaskQueryParaVo.getRedPacketTypeList());
            sopTaskVo.setQueryTime(sopTaskQueryParaVo.getQueryTime());
            sopTaskVo.setDeviceType(sopTaskQueryParaVo.getDeviceType());
            sopTaskVo.setDeviceUniqueIdList(sopTaskQueryParaVo.getDeviceUniqueIdList());
        }

        //发送频率
        sopTaskVo.setRate(sopTask.getRateMax());

        return  sopTaskVo;
    }

    /**
     * 添加SOP任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskDto
     * @return null
     */
    public void addSopTask(SopTaskDto sopTaskDto){

        Merchant merchant = merchantMapper.selectById(sopTaskDto.getMerId());
        if(merchant == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //不是以下2个运营商，则不允许添加
        if(!Lists.newArrayList("13160220183", "15284924496", "13160220184", "13160206693").contains(merchant.getMobile())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "没有权限操作！");
        }

        if(sopTaskDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入类型");
        }

        if(StringUtils.isBlank(sopTaskDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入任务名称");
        }

        if(sopTaskDto.getQueryTime() == null || sopTaskDto.getQueryTime() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入查询时间");
        }

        if(sopTaskDto.getRate() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入发送间隔时间");
        }

        //保存清粉任务
        int now = DateUtil.getNowTime();
        SopTask sopTask = new SopTask();
        sopTask.setId(IdWorker.getId());
        sopTask.setMerId(sopTaskDto.getMerId());
        sopTask.setName(sopTaskDto.getName());
        sopTask.setStatus(SopTaskStatusEnum.INIT.getId());
        sopTask.setType(sopTaskDto.getType());
        SopTaskQueryParaVo sopTaskQueryParaVo = new SopTaskQueryParaVo();
        sopTaskQueryParaVo.setRedPacketTypeList(sopTaskDto.getRedPacketTypeList());
        sopTaskQueryParaVo.setQueryTime(sopTaskDto.getQueryTime());
        sopTaskQueryParaVo.setDeviceType(sopTaskDto.getDeviceType());
        sopTaskQueryParaVo.setDeviceUniqueIdList(sopTaskDto.getDeviceUniqueIdList());
        sopTask.setQueryPara(JSONObject.toJSONString(sopTaskQueryParaVo));
        sopTask.setResend(sopTaskDto.getResend());
        sopTask.setUserTags(Tools.getStrNull(JSONObject.toJSONString(sopTaskDto.getUserTagsList())));
        sopTask.setTags(Tools.getStrNull(JSONObject.toJSONString(sopTaskDto.getTagsList())));
        sopTask.setRemark(sopTaskDto.getRemark());
        sopTask.setMsg(sopTaskDto.getMsg());
        sopTask.setRateMin(sopTaskDto.getRate());
        sopTask.setRateMax(sopTaskDto.getRate());
        sopTask.setBusyTimeInterval(sopTaskDto.getBusyTimeInterval());
        sopTask.setLimitTimeStart(sopTaskDto.getLimitTimeStart());
        sopTask.setLimitTimeEnd(sopTaskDto.getLimitTimeEnd());
        sopTask.setExptime(sopTaskDto.getExptime());
        sopTask.setInterval(0); //默认为0
        sopTask.setCreateTime(now);
        sopTask.setUpdateTime(now);
        sopTaskMapper.insert(sopTask);

        //循环机器人，依次建立每个机器人的添加好友任务
        if(sopTaskDto.getType().intValue() == 1){ //查券未下单
            //sopTaskSyncService.addSopTaskByQueryNoOrder(sopTask);
        }else if(sopTaskDto.getType().intValue() == 2){ //未下单
            sopTaskSyncService.addSopTaskByNoOrder(sopTask);
        }else if(sopTaskDto.getType().intValue() == 3){ //红包未领取
            sopTaskSyncService.addSopTaskByRedNoReceive(sopTask);
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "类型输入有误");
        }
    }

    /**
     * 编辑SOP任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskDto
     * @return null
     */
    public void updateSopTask(SopTaskDto sopTaskDto){

        if(sopTaskDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入类型");
        }

        if(StringUtils.isBlank(sopTaskDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入任务名称");
        }

        if(sopTaskDto.getQueryTime() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入查询时间");
        }

        if(sopTaskDto.getRate() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入发送间隔时间");
        }

        if(sopTaskDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SopTask sopTask = sopTaskMapper.selectById(sopTaskDto.getId(), sopTaskDto.getMerId());

        if(sopTask == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        int now = DateUtil.getNowTime();

        sopTask.setName(sopTaskDto.getName());
        SopTaskQueryParaVo sopTaskQueryParaVo = new SopTaskQueryParaVo();
        sopTaskQueryParaVo.setRedPacketTypeList(sopTaskDto.getRedPacketTypeList());
        sopTaskQueryParaVo.setQueryTime(sopTaskDto.getQueryTime());
        sopTask.setQueryPara(JSONObject.toJSONString(sopTaskQueryParaVo));
        sopTask.setResend(sopTaskDto.getResend());
        sopTask.setUserTags(Tools.getStrNull(JSONObject.toJSONString(sopTaskDto.getUserTagsList())));
        sopTask.setTags(Tools.getStrNull(JSONObject.toJSONString(sopTaskDto.getTagsList())));
        sopTask.setRemark(sopTaskDto.getRemark());
        sopTask.setMsg(sopTaskDto.getMsg());
        sopTask.setRateMin(sopTaskDto.getRate());
        sopTask.setRateMax(sopTaskDto.getRate());
        sopTask.setBusyTimeInterval(sopTaskDto.getBusyTimeInterval());
        sopTask.setLimitTimeStart(sopTaskDto.getLimitTimeStart());
        sopTask.setLimitTimeEnd(sopTaskDto.getLimitTimeEnd());
        sopTask.setExptime(sopTaskDto.getExptime());
        sopTask.setInterval(0); //默认为0
        sopTask.setUpdateTime(now);
        sopTaskMapper.updateById(sopTask);
    }

    /**
     * 删除SOP任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskIdDto
     * @return null
     */
    @Transactional
    public void deleteSopTask(SopTaskIdDto sopTaskIdDto){

        if(sopTaskIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SopTask sopTask = sopTaskMapper.selectById(sopTaskIdDto.getId(), sopTaskIdDto.getMerId());

        if(sopTask == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(sopTask.getStatus().intValue() == SopTaskStatusEnum.INIT.getId().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "初始化中的任务不能删除");
        }

        //删除任务
        sopTaskMapper.deleteById(sopTask.getId(), sopTaskIdDto.getMerId());

        //删除SOP添加明细
        sopTaskAddInfoMapper.deleteByTaskId(sopTask.getId(), sopTaskIdDto.getMerId());

    }

    /**
     * 停止SOP任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskIdDto
     * @return null
     */
    @Transactional
    public void stopSopTask(SopTaskIdDto sopTaskIdDto){

        if(sopTaskIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SopTask sopTask = sopTaskMapper.selectById(sopTaskIdDto.getId(), sopTaskIdDto.getMerId());

        if(sopTask == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(sopTask.getStatus().intValue() == SopTaskStatusEnum.INIT.getId().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "初始化中的任务不能停止");
        }

        sopTask.setStatus(SopTaskStatusEnum.STOP.getId());

        //停止任务
        sopTaskMapper.updateById(sopTask);
    }

    /**
     * 开启SOP任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskIdDto
     * @return null
     */
    @Transactional
    public void startSopTask(SopTaskIdDto sopTaskIdDto){

        if(sopTaskIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SopTask sopTask = sopTaskMapper.selectById(sopTaskIdDto.getId(), sopTaskIdDto.getMerId());

        if(sopTask == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(sopTask.getStatus().intValue() == SopTaskStatusEnum.INIT.getId().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "初始化中的任务不能停止");
        }

        sopTask.setStatus(SopTaskStatusEnum.ADDING.getId());

        //开启任务
        sopTaskMapper.updateById(sopTask);
    }

    /**
     * 重置SOP任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskIdDto
     * @return null
     */
    @Transactional
    public void resetSopTask(SopTaskIdDto sopTaskIdDto){

        if(sopTaskIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SopTask sopTask = sopTaskMapper.selectById(sopTaskIdDto.getId(), sopTaskIdDto.getMerId());

        if(sopTask == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(sopTask.getStatus().intValue() == SopTaskStatusEnum.INIT.getId().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "初始化中的任务不能重置");
        }

        //循环机器人，依次建立每个机器人的添加好友任务
        if(sopTask.getType().intValue() == 1){ //查券未下单
            sopTaskSyncService.addSopTaskByQueryNoOrder(sopTask);
        }else if(sopTask.getType().intValue() == 2){ //未下单
            sopTaskSyncService.addSopTaskByQueryNoOrder(sopTask);
        }else if(sopTask.getType().intValue() == 3){ //红包未领取
            sopTaskSyncService.addSopTaskByRedNoReceive(sopTask);
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "类型输入有误");
        }
    }
}
